// long-poll-server.js
const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors());

let currentVersion = '20250720-001';

// 缓存所有等待中的客户端
let waitingClients = [];


app.get('/version-check', (req, res) => {
    const clientVersion = req.query.version;
    if (clientVersion !== currentVersion) {
        // 客户端版本不是最新，立即通知
        return res.json({ update: true, version: currentVersion });
    }

    // 没更新就挂起请求（最长等待 25 秒）
    const timer = setTimeout(() => {
        res.json({ update: false });
        waitingClients = waitingClients.filter(c => c.res !== res) // 移除对应客户端
    }, 25000);

    waitingClients.push({
        res,
        timer,
        version: clientVersion
    });

    res.on('close', () => {
        clearTimeout(timer);
        waitingClients = waitingClients.filter(c => c.res !== res);
        // 这里可以打印日志或做其他清理工作
        console.log('客户端断开连接，已移除等待队列');
    })
})

// 提供一个手动更新版本的接口
app.get('/update-version/:version', (req, res) => {
    currentVersion = req.params.version;
    // 通知所有等待中的客户端
    waitingClients.forEach(({ res, timer }) => {
        clearTimeout(timer);
        res.json({ update: true, version: currentVersion });
    })
    waitingClients = [];
    res.send(`版本已更新为 ${currentVersion}`);
})

app.listen(3000, () => console.log('服务已启动：http://localhost:3000'));